package com.util;

public class InputCommandUtil {
    /**
     * 获取地址码
     */

    public static String getAddrCode(String cmd){
        return cmd.substring(0,2);
    }

    /**
     *获取命令请求的数据起始地址
     */
    public static String getStarAddr(String cmd){
        return cmd.substring(4,8);
    }
    /**
     *获取命令请求的数据起始地址
     */
    public static int getStarAddrInt(String cmd){
        String starAddr = getStarAddr(cmd);

        return ByteUtil.hexStringToNum(starAddr);
    }
    /**
     *获取命令请求的数据的个数
     */
    public static String getReqDataCount(String cmd){
        return cmd.substring(8,12);
    }
    /**
     *获取命令请求的数据的个数
     */
    public static int getReqDataCountInt(String cmd){
        String reqDataCount = getReqDataCount(cmd);

        return ByteUtil.hexStringToNum(reqDataCount);
    }

    /**
     * 获取crc检验
     * @param cmd
     * @return
     */
    public static String getCrc(String cmd){
        return cmd.substring(12,16);
    }

    /**
     * 获取功能码
     * @param cmd
     * @return
     */
    public static String getFunctionCode(String cmd) {
        return cmd.substring(2,4);
    }

    /**
     * 判断功能码是否是03
     * @param cmd
     * @return
     */
    public static boolean isFuncCode03(String cmd){
        return "03".equals(getFunctionCode(cmd));
    }


    public static boolean isAddrCode01(String cmd){
        if(cmd.length() < 2) return false;
        return "01".equals(getAddrCode(cmd));
    }

    public static boolean isMasterCmd(String cmd){
        if(cmd.length() < 4) return false;
        return isFuncCode03(cmd) && isAddrCode01(cmd)  && cmd.length() == 16;
    }
    public static boolean isSlaveCmd(String msg){
        if(msg.length()<6) return false;
        String length = msg.substring(4, 6);
        int lengthInt = ByteUtil.hexStringToNum(length)*2;
        if(msg.length() == lengthInt+10){
            return true;
        }else{
            return false;
        }
    }

    public static void main(String[] args) {
        String cmd = "010300010003aaaa";
        int starAddrInt = InputCommandUtil.getStarAddrInt(cmd);
        System.out.println(starAddrInt);

        int dataCountInt = InputCommandUtil.getReqDataCountInt(cmd);
        System.out.println(dataCountInt);

        String msg="03030402DE00F239F402030200013D84";
        boolean masterCmd = InputCommandUtil.isMasterCmd(msg);
        boolean slaveCmd = InputCommandUtil.isSlaveCmd(msg);

        if (InputCommandUtil.isMasterCmd(msg) || InputCommandUtil.isSlaveCmd(msg)) {
            //System.out.println("");
        }else{

            System.out.println("丢弃一条数据");
        }

    }
}
